/**
 * create by zhike date:2015年3月12日
 */
package com.acooly.module.openapi.client.provider.baofu.marshall;

import com.acooly.core.utils.Strings;
import com.acooly.module.openapi.client.api.exception.ApiClientException;
import com.acooly.module.openapi.client.api.marshal.ApiUnmarshal;
import com.acooly.module.openapi.client.api.message.MessageFactory;
import com.acooly.module.openapi.client.provider.baofu.domain.BaoFuResponse;
import com.acooly.module.openapi.client.provider.baofu.enums.BaoFuServiceEnum;
import com.acooly.module.openapi.client.provider.baofu.enums.BaoFuServiceIsZIPEnum;
import com.acooly.module.openapi.client.provider.baofu.exception.ApiClientProcessingException;
import com.acooly.module.openapi.client.provider.baofu.marshall.info.ResponseInfo;
import com.acooly.module.openapi.client.provider.baofu.utils.BaoFuSecurityUtil;
import com.acooly.module.openapi.client.provider.baofu.utils.XmlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author zhike
 */
@Service
@Slf4j
public class BaoFuResponseUnmarshall extends BaoFuMarshallSupport
        implements ApiUnmarshal<BaoFuResponse, ResponseInfo> {

    @Resource(name = "baoFuMessageFactory")
    private MessageFactory messageFactory;

    @SuppressWarnings("unchecked")
    @Override
    public BaoFuResponse unmarshal(ResponseInfo responseInfo, String serviceName) {

        if(Strings.isBlank(responseInfo.getMessage())) {
            log.info("请求失败:响应报文为空");
            throw new ApiClientException("请求失败:响应报文为空");
        }
        try {
            //判断响应报文是否需要解压
            BaoFuServiceIsZIPEnum baoFuServiceIsZIP = BaoFuServiceIsZIPEnum.find(serviceName);
            boolean isZip = false;
            if(baoFuServiceIsZIP != null) {
                isZip = true;
            }
            //解密报文
            String decodeDataContent = doDecodeResponse(responseInfo.getMessage(),responseInfo.getPartnerId(),isZip);
            if(!isZip) {
                decodeDataContent = BaoFuSecurityUtil.Base64Decode(decodeDataContent);
            }
            log.info("响应报文:{}", decodeDataContent);
            return doUnmarshall(decodeDataContent, serviceName);
        } catch (Exception e) {
            throw new ApiClientProcessingException("解析响应报文错误:" + e.getMessage());
        }
    }

    protected BaoFuResponse doUnmarshall(String resMessage, String serviceName) {
        BaoFuResponse response =
                (BaoFuResponse) messageFactory.getResponse(BaoFuServiceEnum.find(serviceName).getKey());
        response = XmlUtils.toBean(resMessage, response.getClass());
        return response;
    }

    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }
}
